class Solution {
public:
    int calculateMinimumHP(vector<vector<int>>& dungeon) {
        int n = dungeon.size();
        int m = dungeon[0].size();
        vector<vector<int>>f(n + 1, vector<int>(m + 1, 0));
        for (int i = n - 1; i >= 0; i--) {
            for (int j = m - 1; j >= 0; j--) {
                if (i == n - 1 && j == m - 1) {
                    f[i][j] = max(1, 1 - dungeon[i][j]);
                }
                else if (i == n - 1) {
                    f[i][j] = max(1, f[i][j + 1] - dungeon[i][j]);
                }
                else if (j == m - 1) {
                    f[i][j] = max(1, f[i + 1][j] - dungeon[i][j]);
                }
                else {
                    int mi = min(f[i + 1][j], f[i][j + 1]);
                    f[i][j] = max(1, mi - dungeon[i][j]);
                }
            }
        }
        return f[0][0];
    }
};